<template>
    <div class='role'>
        <div class='leftContent'>
            <el-tree
                :data="data"
                node-key="id"
                ref="roleTree"
                default-expand-all
                @node-click="roleClickEvent"
                :expand-on-click-node="false"
                :render-content="renderContent2">
            </el-tree>
        </div>
        <div class='rightContent'>
            <div class='headers2'>
              {{clickRow.label}}
            </div>
            <el-tabs type="border-card" class='tabs'>
                <el-tab-pane label="模块权限">
                    <div class='modelTrees'>
                         <el-tree
                            :data="modelData"
                            show-checkbox
                            :props="props"
                            node-key="key"
                            ref="modelTree"
                            default-expand-all
                            :render-content="renderContent"
                            :expand-on-click-node="false">
                        </el-tree>
                    </div>
                    
                </el-tab-pane>
                <el-tab-pane label="操作权限">
                    <div class='buttonTrees'>
                         <el-tree
                            :data="buttonData"
                            show-checkbox
                            :props="props2"
                            node-key="keys"
                            ref="buttonTree"
                            default-expand-all
                            :expand-on-click-node="false">
                        </el-tree>
                    </div>
                </el-tab-pane>

                <el-tab-pane label="其他权限">
                    <div class='buttonTrees'>
                        <el-table
                        :data="permissionData"
                        style="width: 100%">
                        <el-table-column
                        label="权限名称"
                        width="420">
                        <template slot-scope="scope">
                            {{ scope.row.name }}
                        </template>
                        </el-table-column>
                        <el-table-column
                        label="值"
                        width="280">
                        <template slot-scope="scope">
                            
                             <el-radio-group v-model="scope.row.rp_ex3" size="medium">
                                <el-radio-button label="是" ></el-radio-button>
                                <el-radio-button label="否"></el-radio-button>
                            </el-radio-group>

                        </template>
                        </el-table-column>
                        
                    </el-table>
                    </div>
                </el-tab-pane>
            </el-tabs>
            <div class='btns2'>
                <el-button type="primary" @click="save">保存</el-button>
            </div>
        </div>

        <el-dialog
            title="角色编辑"
            :visible.sync="dialogVisible"
            width="30%"
            >
            <div>
                <el-form ref="form"  label-width="120px">
                    <el-form-item label="上级角色名称">
                        <el-input v-model="role_parent" readonly="true"></el-input>
                    </el-form-item>
                    <el-form-item label="角色名称">
                        <el-input v-model="role_name"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRole();">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="角色编辑"
            :visible.sync="dialogVisible"
            width="30%"
            >
            <div>
                <el-form ref="form"  label-width="120px">
                    <el-form-item label="上级角色名称">
                        <el-input v-model="role_parent" readonly="true"></el-input>
                    </el-form-item>
                    <el-form-item label="角色名称">
                        <el-input v-model="role_name"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRole();">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="设置查看权限"
            :visible.sync="dialogVisible3"
            width="50%"
            >
            <div>
                <el-form ref="form"  label-width="200px">
                    <el-form-item label="部门选择">
                         <select-tree :data="depart" id="data.departName" :exkey="departExKey"  isMulti="Y"   @input="changeData2"  url="/business/depart/getDepartTreeSelect" style='width:550px'></select-tree>
                        
                    </el-form-item>
                    <el-form-item label="部门为空是否可以查看">
                        <el-select v-model="viewPer.viewDepart" placeholder="部门为空是否可以查看" >
                            <el-option label="可以查看" value="Y"></el-option>
                            <el-option label="不可以查看" value="N"></el-option>
                        </el-select>
                    </el-form-item>
                     <el-form-item label="人员为空是否可以查看">
                         <el-select v-model="viewPer.viewUser" placeholder="人员为空是否可以查看" >
                            <el-option label="可以查看" value="Y"></el-option>
                            <el-option label="不可以查看" value="N"></el-option>
                        </el-select>
                    </el-form-item>
                     <el-form-item label="是否可以查看本部门">
                         <el-select v-model="viewPer.isViewDepart" placeholder="是否可以查看本部门" >
                            <el-option label="可以查看" value="Y"></el-option>
                            <el-option label="不可以查看" value="N"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible3 = false">取 消</el-button>
                <el-button type="primary" @click="saveViewPer();">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import SelectTree  from '../../components/input/SelectTree'
export default {
    components:{
        SelectTree
    },
    data(){
        return{
            depart:{
                data:{
                    departId:"",
                    departName:""
                }
            },
            departExKey:{
                id:"departId"
            },
            viewPer:{
                departId:"",
                departName:"",
                viewDepart:"N",
                isViewDepart:"N",
                viewUser:"N",
                roleId:"",
                userId:"",
                model:"",
                key:""
            },
            dialogVisible:false,
            dialogVisible3:false,
            role_name:'',
            role_parent:"",
            isEdit:false,
            role:{},
            clickRow:{},
            permissionData:[],
            data : [{
                id:"-1",
                label:"角色设置",
                children:[]
            }],
            modelData:[],
            buttonData:[],
            props:{
                label:"text",
                nodeKey:"key",
                key:"key"

            },
             props2:{
                label:"buttonName"

            }
        }
    },
    created(){
        this.loadRole();
        this.loadModel();
        this.loadButton();
    },
    methods:{
        loadRole(){
            this.$post("api","/api/permission/getUserRole",{}).then(data=>{
                console.log(data);
                this.data[0].children=data;
                if(data.length>0){
                    let id=data[0].id;
                    this.clickRow=data[0];
                    this.loadModel();
                    this.loadButton();
                    this.loadPermission();
                    this.$refs.roleTree.setCheckedKeys([id])
                }
                
            })
        },
        loadModel(){
            this.$post("api","/api/permission/getUserModel",{role_id:this.clickRow.id}).then(data=>{
                console.log(data);
                this.modelData=data[0].model;
                this.$refs.modelTree.setCheckedKeys(data[0].checked.split(","))
                console.log(this.modelData)
                console.log(data[0])
            })
        },
        loadPermission(){
           
            this.$post("api","/api/permission/getUserPermission",{role_id:this.clickRow.id}).then(data=>{
                this.permissionData=data;
            })
        },
        savePermission(){
            this.$post("api","/api/permission/saveUserPermission",{roleId:this.clickRow.id,data:JSON.stringify(this.permissionData)}).then(data=>{
                if(data[0].status=="+OK"){
                    this.$message({
                        message: unescape(data[0].msg),
                        type: 'success'
                    });
                   
                }else{
                     this.$message.error(unescape(data[0].msg));
                }
            })
        },
        loadButton(){
            this.$post("api","/api/permission/getRoleButton",{role_id:this.clickRow.id}).then(data=>{
                console.log(data);
                this.buttonData=data[0].button;
                this.$refs.buttonTree.setCheckedKeys(data[0].checked.split(","))
                
            })
        },
        addRole(data){
            this.isEdit=false;
            this.dialogVisible=true;
            this.role_parent=data.label;
            this.role=data;
        },
        changeData2(data){
            let item=JSON.parse(data);
            let value=item.value;
            let label=item.label;
           // alert(value)
            this.viewPer.departId=value;
            this.viewPer.departName=label;
        },
        saveViewPer(){
            this.$post("api","/api/permission/saveUserViewPer",{data:JSON.stringify(this.viewPer)}).then(data=>{
                if(data[0].status=="+OK"){
                    this.$message({
                        message: unescape(data[0].msg),
                        type: 'success'
                    });
                   
                }else{
                     this.$message.error(unescape(data[0].msg));
                }
            })
        },
        saveRole(){
            let id="";
            let pId="";
           
            if(this.isEdit){
                id=this.role.id;
                pId=this.role.parentId;
            }else{
                pId=this.role.id;
            }
           
            this.$post("api","/api/permission/saveUserRole",{pId:pId,role_id:id,role_name:escape(this.role_name)}).then(data=>{
                if(data[0].status=="+OK"){
                    this.$message({
                        message: unescape(data[0].msg),
                        type: 'success'
                    });
                    if(!this.isEdit){
                        const newChild = { id: data[0].id, label:this.role_name,parentId:pId,parentName:this.role_parent,children: [] };
                        this.role.children.push(newChild);
                    }else{
                        this.role.label=this.role_name;
                    }
                     
                    if (!data.children) {
                    this.$set(data, 'children', []);
                    }
                   
                    this.dialogVisible=false;
                    this.role_name="";
                }else{
                     this.$message.error(unescape(data[0].msg));
                }
            })
        },
        editRole(data){
            console.log(data,"editRole===========")
            this.isEdit=true;
            this.dialogVisible=true;
            this.role=data;
            this.role_name=data.label;
            this.role_parent=data.parentName;
        },
        delRole(node,data){
            let id=data.id;
             this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post("api","/api/permission/delUserRole",{role_id:""+id}).then(json=>{
                    if(json[0].status=="+OK"){
                        this.$message({
                            message: unescape(json[0].msg),
                            type: 'success'
                        });
                        const parent = node.parent;
                        const children = parent.data.children || parent.data;
                        const index = children.findIndex(d => d.id === data.id);
                        children.splice(index, 1);
                    }else{
                        
                        this.$message.error(unescape(json[0].msg));
                    }
                     
                })
            }).catch(() => {
              
            });
        },
        remove(node, data) {
            const parent = node.parent;
            const children = parent.data.children || parent.data;
            const index = children.findIndex(d => d.id === data.id);
            children.splice(index, 1);
        },

        renderContent2(h, { node, data, store }) {
            return (
            <span class="custom-tree-node">
                <span>{node.label}</span>
                <span>
                <el-button size="mini" type="text" on-click={ () => this.addRole(data) }>新增</el-button>
                <el-button size="mini" type="text" on-click={ () => this.editRole(data) }>修改</el-button>
                <el-button size="mini" type="text" on-click={ () => this.delRole(node, data) }>删除</el-button>
                </span>
            </span>);
        },
        save(){
            //let data=this.$refs.modelTree.getCheckedKeys();
            let data=[];
            let button=[];
           // let button=this.$refs.buttonTree.getCheckedKeys();


            let data_=this.$refs.modelTree.getCheckedNodes(false,false);
            let button_=this.$refs.buttonTree.getCheckedKeys(false,false);

            console.log(data_);

            for(let i=0;i<data_.length;i++){
                let key=data_[i].key;
                data.push(key);
            }
            for(let i=0;i<button_.length;i++){
                let keys=button_[i];
                button.push(keys);
            }
            console.log("data======================================");
            console.log(data);
            console.log(button)


            let datas=[];
            for(let i=0;i<data.length;i++){
                let d={};
                d.key=data[i];
                datas.push(d);
            }
            console.log(datas);

            let buttons=[];
            for(let i=0;i<button.length;i++){
                let d={};
                d.key=button[i];
                buttons.push(d);
            }
           
            this.$post("api","/api/permission/saveUserModel",{
                role_id:this.clickRow.id,
                data:JSON.stringify(datas),
                buttons:JSON.stringify(buttons)
            }).then(json=>{
                if(json[0].status=="+OK"){
                        this.$message({
                            message: unescape(json[0].msg),
                            type: 'success'
                        });
                    }else{
                        
                        this.$message.error(unescape(json[0].msg));
                    }
            })
            this.savePermission();
        },
        roleClickEvent(data){
            if(data.id=="-1"){
                //alert("不能操作根节点");
                return;
            }
            this.clickRow=data;
            console.log(this.clickRow)
            this.loadModel();
            this.loadButton();
            this.loadPermission();
        },
        openView(data){
            console.log(data,"openView==============================================")
            this.viewPer={
                departId:"",
                departName:"",
                viewDepart:"N",
                isViewDepart:"N",
                viewUser:"N",
                roleId:"",
                userId:"",
                model:data.model,
                key:data.key
            }
            this.dialogVisible3=true;
            this.$post("api","/api/permission/getUserViewPer",{model:data.model,key:data.key,roleId:this.clickRow.id}).then(data=>{
                this.viewPer.departId=data.rvp_ex2;
                this.viewPer.departName=data.rvp_ex7;
                this.viewPer.viewDepart=data.rvp_ex4;
                this.viewPer.isViewDepart=data.rvp_ex8;
                this.viewPer.viewUser=data.rvp_ex5;
                this.viewPer.roleId=data.role_id;
                this.viewPer.userId=data.rvp_ex3;
                this.viewPer.roleId=this.clickRow.id;
                this.depart.data.departId=this.viewPer.departId;
                this.depart.data.departName=this.viewPer.departName;
            })
        },
        renderContent(h, { node, data, store }) {
           return (
            <span class="custom-tree-node">
                <span>{node.label}</span>
                <span>
                <el-button size="mini" type="text" on-click={ () => this.openView(data) }>设置查看权限</el-button>
                </span>
            </span>);
        }
    }
}
</script>
<style scoped>
    .role{
        width:100%;
        height:100%;
        display: flex;
        flex-direction: row;
        box-sizing: border-box;
    }
    .leftContent{
        width:340px;
        height:100%;
        overflow:auto;
        background:#fff;
        border-left:1px solid #ddd;
    }
    .rightContent{
        flex:1;
        display:flex;
        flex-direction: column;
        box-sizing: border-box;
        padding-left:15px;
    }
    .btns2{
        padding-top:15px;
        height:60px;
        text-align: center;
        border:1px solid #ddd;
    }
   .tabs{
        flex:1;
        overflow: hidden;
        display: flex;
        flex-direction: column;
   }
   .modelTrees{
       height:100%;
       overflow: auto;
   }
   .buttonTrees{
       height:100%;
       overflow: auto;
   }
   .headers2{
       height:40px;
       line-height:20px;
       padding:10px;
       box-sizing: border-box;
       background:#fff;
       font-weight: bold;
       border:1px solid #ddd;
       text-align:center;
   }
</style>
<style >
    .custom-tree-node {
        flex: 1 !important;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
    .el-checkbox{
        margin-top:0 !important;
    }
</style>